package Netty.old.NIO.组件.NIOChannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class 文件Copy {
    public static void main(String[] args) {
        File file = new File("File/NIO/zjlInput.txt");
        File file1 = new File("File/NIO/zjlOutput.txt");
//        File file = new File("D:\\Win10Driver\\OneDrive\\桌面\\code-server-3.12.0-linux-amd64.tar.gz");
//        File file1 = new File("D:\\Win10Driver\\OneDrive\\桌面\\code-server-3.2.0-linux-amd64.tar.gz");
        //创建一个缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        文件复制(file, file1,byteBuffer);

    }

    private static void 文件复制(File file, File file1,ByteBuffer byteBuffer) {
        FileInputStream fis = null;//创建一个输入流   内置有通道
        FileOutputStream fos = null;//创建一个输出流   内置有通道
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            fis = new FileInputStream(file);
            fos = new FileOutputStream(file1);
            inputChannel = fis.getChannel();//获取对应的FileChannel
            outputChannel = fos.getChannel();//获取对应的FileChannel
            利用缓冲去复制(byteBuffer, inputChannel, outputChannel);
            /**
             * //在linux下一个transferTo方法就可以完成传输
             * //在windows下- 次调用transferTo只能发送8M，就需要分段传输文件，而且要主要传输时的位置  现在好像没了
             * //transferTo底层使用到零拷贝
             */
//            inputChannel.transferTo(inputChannel.size(),0,outputChannel);///使用零拷贝   使用的是本机内存  谨慎使用
            long k = 0;
            System.out.println(inputChannel.size());
//            while (k+8<<20<inputChannel.size()){
//                outputChannel.transferFrom(inputChannel,k,k+(8<<20));
//                k+=8<<20;
//                System.out.println(k);
//            }
            outputChannel.transferFrom(inputChannel,k,inputChannel.size());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputChannel.close();
                outputChannel.close();
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void 利用缓冲去复制(ByteBuffer byteBuffer, FileChannel inputChannel, FileChannel outputChannel) throws IOException {
        while (inputChannel.read(byteBuffer)>0) {//将通道的信息读入到  Buffer
            byteBuffer.flip();
            //写入到FileChannel 通道
            outputChannel.write(byteBuffer);
            byteBuffer.clear();
        }
    }

}
